<script setup>
import { ref, onMounted,nextTick ,watch} from 'vue'
import { useRoute } from 'vue-router'
import { getCommentAPI, getSubCommentAPI, replyCommentAPI } from '@/api/comment'
import { getDetail } from '@/api/detail';
import { formatTime } from '@/utils/format';
import { useLikeStore } from '@/stores/like';
import { ElMessage } from 'element-plus';
const route = useRoute()
const goods = ref({})
const likeStore = useLikeStore()
const getGoods = async () => {
  const res = await getDetail(route.params.id)
  //console.log(res)
  goods.value = res.result
}
onMounted(() => {
  getGoods()
  getComment()
  likeStore.getLikeList()
})
const data = ref({
  id: route.params.id,
  page: 1,
  pageSize: 5,
  type: 1
})
const comments = ref([])
const getComment = async () => {
  const res = await getCommentAPI(data.value)
  console.log(res)
  comments.value = res.result
  if (Array.isArray(comments.value)){
    comment.value = comments.value.map(item => {
      if(likeStore.likeList.includes(item.id)){
        item.likenum--
      }
      
      return item
    })
  }
}
const disabled = ref(false)
const load = async () => {
  console.log('加载更多');
  data.value.page++
  const res = await getCommentAPI(data.value)
  if (res.result.length === 0) {
    disabled.value = true
    console.log('没有数据了');
  } else {
    comments.value = [...comments.value, ...res.result]
  }
}


//2级评论
const drawer = ref(false)
const subComments = ref([])
const subCommentPage = ref({
  page: 1,
  pageSize: 5
})
const subParentComment = ref({})//负责渲染头部
const comment = ref({
  itemId: route.params.id,
  parentId: '',
  content: '',
  images: []
})//提交

const placeholder = ref('说点什么吧')
const openSubComment = async (item) => {
  drawer.value = true
  subCommentPage.value.page = 1
  subParentComment.value = item
  const { result } = await getSubCommentAPI(item.id, subCommentPage.value.page, subCommentPage.value.pageSize)
  subComments.value = result
  if (comment.value.parentId !== item.id) {
    comment.value.parentId = item.id
    comment.value.content = ''
  }
  placeholder.value = '向' + subParentComment.value.nickname + '说点什么吧'
}
const disabled1 = ref(false)
const load1 = async (id) => {
  //console.log("have2级评论");

  subCommentPage.value.page++
  const { result } = await getSubCommentAPI(id, subCommentPage.value.page, subCommentPage.value.pageSize)
  if (result.length === 0) {
    disabled1.value = true
    console.log("没有数据了");
  } else {
    subComments.value = [...subComments.value, ...result]
  }
}

const replyComment = async () => {
  if (!comment.value.content) {
    ElMessage.warning('请输入评论内容')
    return
  }
  subParentComment.value.replynum++
  await replyCommentAPI(comment.value).then(async () => {
    ElMessage.success('评论成功')
    comment.value.content = ''
    subCommentPage.value.page = 1
    subCommentPage.value.pageSize = 5
    const { result } = await getSubCommentAPI(comment.value.parentId, subCommentPage.value.page, subCommentPage.value.pageSize)
    subComments.value = result
  })
}


const inputRef = ref(null)
const handleClick = async (name) => {
  placeholder.value = '向' + name + '说点什么吧！'
  await nextTick();
  if (inputRef.value)
    inputRef.value.$el.querySelector('textarea').focus();
}

// 将 value1 的初始值设置为 options 数组中存在的选项值

const options = [
  {
    value: 1,
    label: '默认',
  },
  {
    value: 2,
    label: '最新',
  },
  {
    value: 3,
    label: '点赞数',
  },
  {
    value: 4,
    label: '回复数',
  },
];

watch(
  () => data.value.type, // 源：一个 getter 函数，返回 data.value.type
  () => {
    data.value.page = 1
    disabled.value = false
    getComment()
  }
);

//
const handleClickDislike = (id) => {
   likeStore.dislikeComment(id)
}
</script>

<template>
  <div class="container">
    <div class="top1">
      <div class="bread-container" v-if="goods.details">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <!-- 直接使用`goods.categories.[1].id`报错
          原因：一开始goods为`{}`,{}.categories为undefined,undefined[1]就是错的
          解决：?. ( goods.categories?.[1].id ) 或者 v-if
           -->
        <el-breadcrumb-item :to="{ path: `/category/${goods.categories[1].id}` }">{{ goods.categories[1].name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/category/sub/${goods.categories[0].id}` }">{{ goods.categories[0].name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: `/detail/${goods.id}` }">{{ goods.name }}</el-breadcrumb-item>
        <el-breadcrumb-item>评论</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="select">
      <el-select v-model="data.type" placeholder="Select" style="width: 120px">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    </div>
    </div>
    <div class="comment-container">
      <ul v-infinite-scroll="load" :infinite-scroll-disabled="disabled">
        <li v-for="item in comments" :key="item.id">
          <div class="left">
            <div>{{ item.nickname }}</div>
            <img :src="item.avatar" alt="">
          </div>
          <div class="right">
            <div class="comment-images" v-if="item.images && item.images.length !== 0">
              <img v-for="img in item.images" :key="img" :src="img" alt="">
            </div>
            <div class="comment-rate">
              <el-rate v-model="item.rate" disabled show-score text-color="#ff9900" score-template="{value} points" />
            </div>
            <div class="comment-info">
              <div>{{ item.content }}</div>
              <div class="comment-time"><span>{{ goods.name }}</span> <span>{{ formatTime(item.createTime) }}</span>
                <span class="icon " @click="openSubComment(item)"><i class="iconfont icon-pinglun icon1"
                    style="margin-right:5px;"></i>{{ subParentComment.id === item.id ? subParentComment.replynum : item.replynum }}</span>
                <span v-if="!likeStore.likeList.includes(item.id)" @click="likeStore.likeComment(item.id)"><i
                    class="iconfont icon-dianzan icon1" style="margin-right:5px;"></i>{{ item.likenum }}</span>
                <span v-else @click="handleClickDislike(item.id)"><i class="iconfont icon-like-fill icon1"
                    style="margin-right:5px;"></i>{{ item.likenum+1  }}</span>
              </div>
            </div>

          </div>
        </li>
      </ul>
    </div>

    <el-drawer v-model="drawer" title="I am the title" :with-header="false" size="50%">
      <div class="drawer-content">
        <div class="top">
          <div class="left">
            <div>{{ subParentComment.nickname }}</div>
            <img :src="subParentComment.avatar" alt="">
          </div>
          <div class="right">
            <div class="comment-images" v-if="subParentComment.images && subParentComment.images.length !== 0">
              <img v-for="img in subParentComment.images" :key="img" :src="img" alt="">
            </div>
            <div class="comment-rate">
              <el-rate size="large" v-model="subParentComment.rate" disabled show-score text-color="#ff9900"
                score-template="{value} points" />
            </div>
            <div class="comment-info">
              <div>{{ subParentComment.content }}</div>
              <div class="comment-time"><span>{{ goods.name }}</span> <span>{{ formatTime(subParentComment.createTime)
                  }}</span>
              </div>
            </div>
          </div>
        </div>

        <div v-if="subComments.length === 0" class="mid">
          <el-empty description="还没有人回复他，来做第一个回他的人吧">
          </el-empty>
        </div>

        <div class="mid" v-else>
          <ul v-infinite-scroll="() => load1(subParentComment.id)" :infinite-scroll-disabled="disabled1">
            <li v-for="item in subComments" :key="item.id">
              <div class="left">
                <div>{{ item.nickname }} </div>
                <img :src="item.avatar" alt="">
              </div>
              <div class="right">
                <div class="comment-images" v-if="item.images && item.images.length !== 0">
                  <img v-for="img in item.images" :key="img" :src="img" alt="">
                </div>

                <div class="comment-info">
                  <div>{{ item.content }}</div>
                  <div class="comment-time"><span>{{ formatTime(item.createTime) }}</span>
                    <span style="margin-left: 400px;" @click="handleClick(item.nickname)"><i
                        class="iconfont icon-pinglun icon1" style="margin-right:5px;"></i></span>
                  </div>
                </div>

              </div>
            </li>
          </ul>
        </div>
        <div class="end">
          <el-row :gutter="20">
            <el-col :span="21">
              <el-input ref="inputRef" type="textarea" :rows="4" v-model="comment.content" :placeholder=placeholder />
            </el-col>
            <el-col :span="3">
              <el-button  type="primary" style="height: 100%;" @click="replyComment">回复</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.bread-container {
  padding: 25px 0;
}

.top1 {
  display: flex; /* 使用弹性布局 */
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 两端对齐，中间留空 */
}
.bread-container {
  flex: 1; /* 占据左半部分空间 */
}
.select {
  flex: 1; /* 占据右半部分空间 */
  display: flex;
  justify-content: flex-end; /* 将 select 靠右对齐 */
}
.el-breadcrumb,
.el-select {
  height: 100%; /* 让面包屑和选择器高度一致 */
}

/* 调整下拉选项的样式 */
.el-select-dropdown__item {
  padding: 4px 8px; /* 减小内边距，让选项更紧凑 */
  margin: 0;
  font-size: 12px; /* 适当减小字体大小 */
  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 当文字过长时显示省略号 */
}

.comment-container{

  ul {
    list-style-type: none;
    padding: 0;
  }
  li {
    display: flex;
    align-items: flex-start;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
  }
  li:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  }
}

.left {
  flex: 0 0 auto;
  margin-right: 16px;
  text-align: center;
}

.left img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.right {
  flex: 1 1 auto;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 8px;
}

.comment-images img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.comment-rate {
  margin-bottom: 8px;
}

.comment-info {
  color: #333;
  line-height: 1.5;
  font-size: 20px;
}

.comment-time {
  color: #999;
  font: 13px sans-serif;
  margin-top: 20px;

  span {
    margin-right: 8px;
  }
}

.icon {
  margin-left: 600px;
  margin-right: 100px;

}

.icon1 {
  &:hover {
    color: red;
    cursor: pointer;
  }
}

.drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.top {
  flex-shrink: 0;
  // background-color: #f0f0f0;
  padding: 10px;
}

.mid {
  flex-grow: 1;
  overflow-y: auto;
  padding: 10px;
}

.end {
  flex-shrink: 0;
  background-color: #f0f0f0;
  padding: 10px;
}
</style>